<?php

declare(strict_types = 1);

namespace Tools\Helper;

use Tools\DataStructure\Closure;

/**
 * class AutoRestart
 *
 * @package Tools\Helper
 */
class AutoRestart
{
    /**
     * Handler
     *
     * @param string $directory
     * @param Closure $closure
     * @return void
     */
    public static function simpleMonitor(string $directory, Closure $closure)
    {
        Restart:

        $pid = pcntl_fork();

        if ($pid > 0) {
            $fd = inotify_init();
            $watch_descriptor = inotify_add_watch($fd, $directory, IN_MODIFY);

            $events = inotify_read($fd);

            posix_kill($pid, SIGTERM);

            fclose($fd);

            pcntl_wait($status);

            goto Restart;
        } else if ($pid == 0) {
            $closure->execute();
        } else {
            exit(0);
        }
    }

    public static function handle(array $directoryList, Closure $closure)
    {
        (new InotifyMonitor($directoryList))->run();
    }
}
